package com.empresa.iflex.core;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

import com.empresa.iflex.R;
import com.empresa.iflex.database.IFlexDbAdapter;

public class Ver extends ListActivity {
	
	private IFlexDbAdapter ida;
	private SQLiteDatabase db;
	Cursor c;
	private static final int DELETE_ID = Menu.FIRST+3;
	

	/* Chamada quando o programa eh inicializado */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.historico);
      
        this.ida = new IFlexDbAdapter(getApplicationContext());
		this.db = ida.wOpen();
        
		c = Percurso.findAll(db); 
        startManagingCursor(c);
        
    	String[] colunas = new String[]{"datatime", "distancia", "preco", "combustivel", "percurso", "media"};
    	int[] to = new int[]{R.id.tdata, R.id.tdistancia, R.id.tpreco, R.id.tcombustivel, R.id.tpercurso, R.id.tmedia};
    	
    	ListAdapter la = new SimpleCursorAdapter(getApplicationContext(), R.layout.colunas, c, colunas, to);
    	
    	setListAdapter(la);
    	registerForContextMenu(getListView());
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v,
    		ContextMenu.ContextMenuInfo menuInfo) {
    	
    	AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            return;
        }

        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);        
        menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex("datatime")));
    	menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete").setAlphabeticShortcut('d');
        
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    		case DELETE_ID:
    			AdapterView.AdapterContextMenuInfo info=
    				(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();   			
    			Percurso.delete(db, info.id);   			
    			c.requery(); 
    			return(true);
    	}
    	return(super.onOptionsItemSelected(item));
    }
    
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	
    	if (db != null){
    		db.close();
    		ida.close();
    	}
    }
	
}
